<?php
namespace app\api\service;

use think\facade\Log;
use think\facade\Db;

class CallbackService
{
    /**
     * 处理回调日志并记录到主日志
     */
    public static function processCallbackLogs()
    {
        $runtimePath = runtime_path();
        $pattern = $runtimePath . 'callback_*.log';
        
        // 获取所有回调日志文件
        $files = glob($pattern);
        
        foreach ($files as $file) {
            try {
                // 读取日志内容
                $content = file_get_contents($file);
                
                // 从文件名提取订单号
                preg_match('/callback_([^.]+)\.log$/', $file, $matches);
                $orderNumber = $matches[1] ?? '';
                
                if (empty($orderNumber)) {
                    continue;
                }
                
                // 解析HTTP响应
                $success = self::parseResponse($content);
                
                if ($success) {
                    Log::info('异步回调通知成功', [
                        'order_number' => $orderNumber,
                        'log_file' => basename($file)
                    ]);
                } else {
                    Log::error('异步回调通知失败', [
                        'order_number' => $orderNumber,
                        'log_file' => basename($file),
                        'response' => $content
                    ]);
                }
                
                // 删除已处理的日志文件
                unlink($file);
                
            } catch (\Exception $e) {
                Log::error('处理回调日志异常', [
                    'file' => $file,
                    'error' => $e->getMessage()
                ]);
            }
        }
    }
    
    /**
     * 解析curl响应内容
     */
    private static function parseResponse($content)
    {
        // 查找HTTP状态码
        if (preg_match('/HTTP\/\d\.\d\s+(\d+)/', $content, $matches)) {
            $httpCode = (int)$matches[1];
            if ($httpCode >= 200 && $httpCode < 300) {
                // 尝试解析JSON响应
                if (preg_match('/\{.*\}/s', $content, $jsonMatches)) {
                    $data = json_decode($jsonMatches[0], true);
                    if ($data && isset($data['code']) && $data['code'] == 200) {
                        return true;
                    }
                }
                return true; // HTTP 200也算成功
            }
        }
        
        return false;
    }
}

